﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using FOBTV.Web.MainClass;
using iTextSharp.text;
using System.IO;
using iTextSharp.text.pdf;

namespace FOBTV.Web.FOBTV2011.UserControl
{
	public partial class CustomerListControl : System.Web.UI.UserControl
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			// 在此处放置用户代码以初始化页面
			btnfirst.Text = "最首页";
			btnprev.Text = "前一页";
			btnnext.Text = "下一页";
			btnlast.Text = "最后页";

			if (!IsPostBack)
			{
				bindgrid();
			}
		}

		//生成PDF事件
		public void itemsgrid_command(object sender, DataGridCommandEventArgs e)
		{
			string customerId = "";
			switch (((Button)e.CommandSource).CommandName)
			{
				case "createPdf":
					customerId = (e.Item.Cells[0].Text).ToString();
					break;
			}

			MainClass.DBClass DBClassTmp = new MainClass.DBClass();
			System.Data.OleDb.OleDbConnection Conn = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("..\\..\\DB\\FOBTVweb.mdb"));

			GetUserInfo user = new GetUserInfo();
			user.Conn = Conn;
			User userInfo = user.GetUserInfoForPDF(customerId);

			ShowPDFInfo(userInfo);
		}

		//生成PDF
		private void ShowPDFInfo(User userInfo)
		{
			//定义一个Document，并设置页面大小为A4，竖向
			iTextSharp.text.Document doc = new Document(PageSize.A4);
			try
			{
				//写实例
				string fileName = Request.PhysicalApplicationPath + @"PDF\" + userInfo.CustomerID + ".pdf";
				string imagePath = Path.Combine(Request.PhysicalApplicationPath, @"FOBTV2011\images\Name.jpg");
				PdfWriter.GetInstance(doc, new FileStream(fileName, FileMode.Create));


				//打开document
				doc.Open();
				//载入字体
				BaseFont.AddToResourceSearch("iTextAsian.dll");
				BaseFont.AddToResourceSearch("iTextAsianCmaps.dll");


				//"UniGB-UCS2-H" "UniGB-UCS2-V"是简体中文，分别表示横向字 和 纵向字
				//"STSong-Light"是字体名称
				//BaseFont baseFT = BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
				//baseFT.setFontAndSize(bf, 10);
				Font fontBase = new Font(Font.TIMES_ROMAN, 10, Font.NORMAL);
				Font fontBold = new Font(Font.TIMES_ROMAN, 10, Font.BOLD);
				Font fontBaseBlue = new Font(Font.TIMES_ROMAN, 10, Font.NORMAL, Color.BLUE);
				Font fontOther = new Font(Font.TIMES_ROMAN, 9, Font.NORMAL);

				Anchor anchor = new Anchor("NERC-DTV www.fobtv-china.org", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 10, Font.UNDERLINE, new Color(0, 0, 255)));
				anchor.Reference = "http://www.fobtv-china.org";
				anchor.Name = "NERC-DTV www.fobtv-china.org";
				Anchor anchor2 = new Anchor("http://www.fmprc.gov.cn/eng/wjb/zwjg/2490/", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 10, Font.UNDERLINE, new Color(0, 0, 255)));
				anchor2.Reference = "http://www.fmprc.gov.cn/eng/wjb/zwjg/2490/";
				anchor2.Name = "http://www.fmprc.gov.cn/eng/wjb/zwjg/2490/";
				Anchor anchor3 = new Anchor("http://www.FOBTV.org", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 10, Font.UNDERLINE, new Color(0, 0, 255)));
				anchor3.Reference = "http://www.FOBTV.org";
				anchor3.Name = "http://www.FOBTV.org";

                DateTime creatPDFTime = DateTime.Now;
                if (FOBTV.Web.MainClass.SessionState.CurrentUser.State != 5)
                {
                    creatPDFTime = FOBTV.Web.MainClass.SessionState.CurrentUser.CreatPDFTime;
                }
                doc.Add(new Paragraph(GetEnglishFormatDateInfo(creatPDFTime), fontBase));
				doc.Add(new Paragraph(string.Format("{0} {1},{2}", userInfo.FirstName, userInfo.LastName, userInfo.BusinessTitle), fontBase));
				doc.Add(new Paragraph(userInfo.FullCompanyName, fontBase));
				doc.Add(new Paragraph(string.Format("{0},{1}", userInfo.Address, userInfo.PostalCode), fontBase));
				doc.Add(new Paragraph(string.Format("Passport: {0}", userInfo.Passport), fontBase));
				string dateinfo = GetEnglishFormatDateInfo(userInfo.Birthday.Date);
				doc.Add(new Paragraph(string.Format("Birth Date: {0}", dateinfo), fontBase));
				doc.Add(new Paragraph(" ", fontBase));
				doc.Add(new Paragraph(" ", fontBase));
				doc.Add(new Paragraph(" ", fontBase));
				doc.Add(new Paragraph(string.Format("Dear {0} {1} {2}:", userInfo.Prefix, userInfo.FirstName, userInfo.LastName), fontBold));
				doc.Add(new Paragraph("Thank you for your request for a letter of invitation to participate in the FOBTV2011 Summit in Shanghai, China: Conference 10-11, November 2011.", fontBase));
				doc.Add(new Paragraph(" ", fontBase));
				doc.Add(new Paragraph("Future of Broadcast Television (FOBTV) will be held to foster global collaboration that may lead to the development of common strategies for the future of terrestrial broadcasting and to exchange technical advances in the rapidly converging areas of terrestrial broadcasting, consumer electronics and networking technologies. Industry technology leaders are to be invited to work together to share their visions of the future of broadcasting. Bringing together the collective perspectives of experts worldwide should benefit industry leaders as they identify their optimum national path for terrestrial broadcasting. ", fontBase));
				doc.Add(new Paragraph(" ", fontBase));
				doc.Add(new Paragraph("FOBTV 2011  Host Organization:", fontBold));


				Paragraph myParagraph1 = new Paragraph("National Engineering Research Center of Digital Television (", fontBase);
				myParagraph1.Add(anchor);
				myParagraph1.Add(new Chunk(")", fontBase));
				doc.Add(myParagraph1);


				doc.Add(new Paragraph(" ", fontBase));
				doc.Add(new Paragraph("FOBTV 2011 Date and Venue: ", fontBold));
				doc.Add(new Paragraph("Date: 10-11th Nov 2011", fontBase));
				doc.Add(new Paragraph(string.Format("{0}: {1}", "Venue", "Shanghai International Convention Center"), fontBase));
				doc.Add(new Paragraph("Add: 2727, Riverside Avenue, Pudong, Shanghai, China", fontBase));
				doc.Add(new Paragraph(" ", fontBase));
				doc.Add(new Paragraph("It is important to note that visiting China may require you to obtain a temporary visa. We strongly urge you to contact the visa section of the China Embassy/Consulate nearest you to determine how and when to apply for a visa. ", fontBase));


				Paragraph myParagraph2 = new Paragraph("You can visit the website: ", fontBase);
				myParagraph2.Add(anchor2);
				myParagraph2.Add(new Chunk(" or visit our website: ", fontBase));
				myParagraph2.Add(anchor3);
				myParagraph2.Add(new Chunk(" for detailed information about procedures, types of visas, and the time required for processing.", fontBase));
				doc.Add(myParagraph2);


				doc.Add(new Paragraph(" ", fontBase));
				doc.Add(new Paragraph("Sincerely,", fontBase));
				iTextSharp.text.Image jpeg = iTextSharp.text.Image.GetInstance(imagePath);
				jpeg.Alignment = Element.ALIGN_LEFT;
				doc.Add(jpeg);

				doc.Add(new Paragraph(" ", fontBase));
				doc.Add(new Paragraph("Mr.Pingjian Xia ", fontBase));
				doc.Add(new Paragraph("President", fontBase));
				doc.Add(new Paragraph("National Engineering Research Center of Digital Television", fontBase));
                doc.Add(new Paragraph("Tel:86-21-60897266*5015", fontBase));
                doc.Add(new Paragraph("E-mail: pj.xia@nercdtv.org", fontBase));

				//关闭document
				doc.Close();
				Response.Redirect("/PDF/" + userInfo.CustomerID + ".pdf");
				//Response.Write("<script>window.open('../PDF/" + this.lblUserID.Text + ".pdf','_blank')</script>");
			}
			catch (DocumentException de)
			{
			}
			catch (IOException io)
			{
			}

		}

		private string GetEnglishFormatDateInfo(DateTime inputStr)
		{
			string outputStr = "";
			if (inputStr != null)
			{
				System.Globalization.CultureInfo c = System.Globalization.CultureInfo.CreateSpecificCulture("en");
				outputStr = inputStr.ToString("D", c.DateTimeFormat);
				outputStr = outputStr.Substring(outputStr.IndexOf(',') + 1);
			}
			return outputStr;
		}

		//用于显示"第几页,总*页"
		private void showstats()
		{
			lblcurrentindex.Text = "第 " + (dgCustomsers.CurrentPageIndex + 1).ToString() + " 页";
			lblpagecount.Text = "总共 " + dgCustomsers.PageCount.ToString() + " 页";
		}

		//响应分页按钮
		public void pagerbuttonclick(object sender, EventArgs e)
		{
			string arg = ((LinkButton)sender).CommandArgument.ToString();
			switch (arg)
			{
				case "next":
					if (dgCustomsers.CurrentPageIndex < (dgCustomsers.PageCount - 1))
					{
						dgCustomsers.CurrentPageIndex += 1;
					}
					break;
				case "prev":
					if (dgCustomsers.CurrentPageIndex > 0)
					{
						dgCustomsers.CurrentPageIndex -= 1;
					}
					break;
				case "last":
					dgCustomsers.CurrentPageIndex = (dgCustomsers.PageCount - 1);
					break;
				default:
					dgCustomsers.CurrentPageIndex = System.Convert.ToInt32(arg);
					break;
			}
			bindgrid();
			showstats();
		}

		//绑定数据
		private void bindgrid()
		{
			int pageindex = dgCustomsers.CurrentPageIndex + 1;
			MainClass.DBClass DBClassTmp = new MainClass.DBClass();
			string strSQL = "";
			if (pageindex == 1)
                strSQL = "select top 50  CustomerID,Prefix,(FirstName +' '+LastName) as Name,Format(Birthday, 'yyyy-mm-dd') as Birthday,Passport,BusinessTitle,FullCompanyName,URL,Address,PostalCode,City,State,Country,Moblie,Email,MemberShip,Format(CreateTime, 'yyyy-mm-dd') as CreateTime,Format(PayTime, 'yyyy-mm-dd') as PayTime from CustomerInfo order by CustomerID desc";
			else
				strSQL = "SELECT top 50 * FROM CustomerInfo where CustomerID not in(select top " + ((pageindex - 1) * 50).ToString() + " CustomerID from CustomerInfo order by CustomerID desc)  order by CustomerID desc";
			System.Data.OleDb.OleDbConnection Conn = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("..\\..\\DB\\FOBTVweb.mdb"));
			DataSet ds = DBClassTmp.GetDataSet(strSQL, Conn);

			dgCustomsers.DataSource = ds;
			dgCustomsers.DataBind();
			showstats();
		}

	}
}